import datetime
import sys
import threading
import tkinter as tk
from tkinter import ttk
import shutil
import re

import openpyxl
import win32con
import win32ui

from tools_pmc import (chengtao_sn,
                       lj_tyl
                       )


def fun_timer():
    root.after(50, refresh)
    global timer
    timer = threading.Timer(0.05, fun_timer)
    timer.start()


def refresh():
    if combobox1.get() != "" and combobox2.get() != "":
        btn.config(state=tk.NORMAL)
        timer.cancel()


def cfdlg():
    open_flags = win32con.OFN_FILEMUSTEXIST | win32con.OFN_PATHMUSTEXIST
    dlg = win32ui.CreateFileDialog(1, None, None, open_flags, None)  # 1表示打开文件对话框
    dlg.SetOFNTitle("打开表格")
    dlg.DoModal()
    return dlg.GetPathName().replace('\\', "/")


def button_click():
    # 创建一个新线程
    t = threading.Thread(target=show_selected_date)
    # 启动线程
    t.start()


def show_selected_date():
    btn.config(state=tk.DISABLED)
    combobox1.config(state=tk.DISABLED)
    combobox2.config(state=tk.DISABLED)

    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：正在导入通用物料表......\n")
    wb_tyl = openpyxl.load_workbook(lj_tyl)
    ws_tyl = wb_tyl.worksheets[0]
    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：通用物料表导入成功\n")

    wb1 = openpyxl.load_workbook(lj)
    ws1 = wb1.worksheets[0]

    list_result = []
    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：处理中......\n")
    progressbar['maximum'] = ws1.max_row
    for j in range(1, ws1.max_row + 1):
        progressbar['value'] = j
        root.update()
        if str(ws1.cell(j, list1.index(combobox1.get()) + 1).value)[0] == "3" and len(
                str(ws1.cell(j, 3).value)) == 12:
            x = int(ws1.cell(j, 3).value)
            list_result.append(chengtao_sn(x, ws_tyl))
            ws1.cell(j, 4).value = chengtao_sn(x, ws_tyl)
        else:
            list_result.append(None)
    list_result.append(list1.index(combobox2.get()) + 1)
    text.insert('end', datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + "：处理完成！\n")
    wb1.save(r"C:\Users\10352\Desktop\写入成套数据.xlsx")
    file = open(r"\\192.168.70.101\19计划管理部\01.计划\1，数据处理工具\Tools\PMCtools_Python_v2.0\快捷工具\result.txt",
                'w')
    file.write(str(list_result))


list1 = []
for i in range(65, 91):
    list1.append(chr(i))

root = tk.Tk()
root.title("MCtool 成套信息")
# root.geometry('600x200')
root.geometry("+750+400")
root.resizable(False, False)

frame1 = tk.Frame(root)
frame1.pack(side="top", anchor="nw")

label1 = tk.Label(frame1, text="选择品号列位置：")
label1.pack(padx=5, pady=5, side="left")
combobox1 = ttk.Combobox(frame1, values=list1)
combobox1.pack(padx=5, pady=5, side="left")

frame2 = tk.Frame(root)
frame2.pack(side="top", anchor="nw")

label2 = tk.Label(frame2, text="选择写入列位置：")
label2.pack(padx=5, pady=5, side="left")
combobox2 = ttk.Combobox(frame2, values=list1)
combobox2.pack(padx=5, pady=5, side="left")
btn = ttk.Button(frame2, text="确认", command=button_click)
btn.pack(padx=5, pady=5, side="left")

text = tk.Text(root, width=60, height=10)
text.pack(padx=5, pady=5)

progressbar = ttk.Progressbar(root, length=480)
progressbar.pack(padx=5, pady=5)

try:
    lj = sys.argv[1]
except IndexError:
    lj = cfdlg()
name = sys.argv[2]
lj_beifen ="//192.168.70.101/19计划管理部/01.计划/1，数据处理工具/Tools/PMCtools_Python_v2.0/QuickTools/文件备份/"+name+str(datetime.datetime.now())+".xlsx"
shutil.copyfile(lj,lj_beifen)

print(name)
shutil.move('old_name.txt', 'new_name.txt')
btn.config(state=tk.DISABLED)

timer = threading.Timer(1, fun_timer)
timer.start()

root.mainloop()
